import { Component, OnInit } from '@angular/core';
import {FormObjModel} from '../formObj.model';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {Message, TreeNode} from 'primeng/primeng';
import {ActivatedRoute, Router} from '@angular/router';
import {RequestForServiceService} from '../request-for-service.service';
import {PublicService} from '../../services/public.service';
import {EventBusService} from '../../services/event-bus.service';
import {StorageService} from '../../services/storage.service';
import {PUblicMethod} from '../../services/PUblicMethod';
import {environment} from '../../../environments/environment';

@Component({
  selector: 'app-edit-accept-service',
  templateUrl: './edit-accept-service.component.html',
  styleUrls: ['./edit-accept-service.component.scss']
})
export class EditAcceptServiceComponent implements OnInit {
    formObj: FormObjModel;
    myForm: FormGroup;
    options: Object = {
        '来源': [],
        '服务类型': [],
        '所属系统': [],
        '影响度': [],
        '紧急度': [],
        'departments': [],
    };
    displayPersonel: boolean = false;              // 人员组织组件是否显示
    zh: Object;
    message: Message[] = [];               // 交互提示弹出框
    ip: string;
    display: boolean = false;
    filesTree4: TreeNode[] = [];
    selected: Array<any> = [];
    formTitle: string;
    defaultOption: Object = {
        'acceptor': null,
        'acceptor_name': null,
        'acceptor_pid': null,
        'fromx': null,
        'type': null,
        'bt_system': null,
        'influence': null,
        'urgency': null,
    };


    constructor(private activatedRouter: ActivatedRoute,
                private router: Router,
                private rfsService: RequestForServiceService,
                private publicService: PublicService,
                private eventBusService: EventBusService,
                private storageService: StorageService,
                private fb: FormBuilder) {
    }

    ngOnInit() {
        this.createForm();
        this.getOptions();
        this.getUser();
        this.formObj = new FormObjModel();
        this.zh = new PUblicMethod().initZh();
        this.formObj.sid = this.activatedRouter.snapshot.paramMap.get('id');
        this.formObj.status = this.activatedRouter.snapshot.paramMap.get('status');
        this.formTitle = '创建服务请求';
        this.formObj.create_time = PUblicMethod.formateEnrtyTime( new Date() );
        this.formObj.occurrence_time = PUblicMethod.formateEnrtyTime( new Date() );
        this.fb = new FormBuilder();
        this.ip = environment.url.management;
        if (this.formObj.sid) {
            this.formTitle = '编辑服务请求';
            this.getTirckMessage(this.formObj.sid);
            this.rfsService.getFlowChart(this.formObj.status).subscribe(res => {
                this.eventBusService.rfs.next(res);
            });
        }

    }
    getUser() {
        this.publicService.getUser().subscribe(res => {
            this.formObj.creator = res.name;
        });
    }
    createForm() {
        this.myForm = this.fb.group({
            'fromx': '',
            'type': '',
            'submitter': '',
            'title': '',
            'content': '',
            'acceptor': ''
        });
    }
    getOptions() {
        this.rfsService.getParamOptions().subscribe(res => {
            this.options = res;
            if (!this.formObj.sid) {
                this.getPrority(res['影响度'][0]['name'], res['紧急度'][0]['name']);
            }
            this.formObj.fromx = res['来源'][0]['name'];
            this.formObj.type = res['服务类型'][0]['name'];
            this.formObj.bt_system = res['所属系统'][0]['name'];
            this.formObj.influence = res['影响度'][0]['name'];
            this.formObj.urgency = res['紧急度'][0]['name'];
        });
    }
    showTreeDialog( opType ) {
        switch (opType) {
            case 'submitter':
                this.displayPersonel = true;
                break;
            case 'department':
                this.display = true;
                this.publicService.getDepartmentDatas().subscribe(res => {
                    this.filesTree4 = res;
                });
        }

    }
    clearTreeDialog(opType) {
        switch (opType) {
            case 'submitter':
                this.formObj.submitter = '';
                this.formObj.submitter_pid = '';
                this.formObj.submitter_org_oid = '';
                this.formObj.submitter_org = '';
                this.formObj.submitter_phone = '';
                break;
            case 'department':
                this.formObj.acceptor = '';
                this.formObj.acceptor_org = '';
                this.formObj.acceptor_org_oid = '';
                this.formObj.acceptor_pid = '';
                break;
        }

    }
    dataEmitter(event) {
        this.formObj.submitter = event.name;
        this.formObj.submitter_pid = event.pid;
        this.formObj.submitter_org_oid = event.oid;
        this.formObj.submitter_org = event.organization;
        this.formObj.submitter_phone = event.mobile;
    }
    displayEmitter(event) {
        this.displayPersonel = event;
    }
    onFocus() {
        if (this.formObj.influence['name']) {
            this.formObj.influence = this.formObj.influence['name'];
        }
        if (this.formObj.urgency['name']) {
            this.formObj.urgency = this.formObj.urgency['name'];
        }
        this.getPrority(this.formObj.influence, this.formObj.urgency);
    }
    getPrority(influency, urgency) {
        console.log(influency, urgency);
        if ( influency && urgency ) {
            this.rfsService.getPrority( influency, urgency ).subscribe(res => {
                if (res) {
                    this.formObj.priority = res['priority'];
                    this.getDeadline(influency, urgency, res['priority']);
                }
            });
        }
    }
    getDeadline(influency, urgency, prority) {
        if ( influency && urgency && prority ) {
            this.rfsService.getDeadline( influency, urgency, prority, this.formObj.create_time).subscribe(res => {
                if (res) {
                    this.formObj.deadline = res['time_deadline'];
                }
            });
        }
    }
    onBeforeUpload(event) {
        let token = this.storageService.getToken('token');
        event.formData.append('access_token', token);
    }
    onUpload(event) {
        let xhrRespose = JSON.parse(event.xhr.response);
        if ( xhrRespose.errcode && xhrRespose.errcode === '00000' ) {
            this.formObj.attachments = xhrRespose['datas'];
            this.message = [];
            this.message.push({severity: 'success', summary: '消息提示', detail: '上传成功'});
        }else {
            this.message = [];
            this.message.push({severity: 'error', summary: '消息提示', detail: `上传失败${xhrRespose.errmsg}`});
        }
    }
    nodeExpand(event) {
        if (event.node) {
            this.publicService.getDepartmentDatas(event.node.oid, event.node.dep).subscribe(res => {
                event.node.children  = res;
            });
        }
    }
    closeTreeDialog() {
        this.display = false;
        this.formObj.acceptor_org = this.selected['label'];
        this.formObj.acceptor_org_oid = this.selected['oid'];
        this.getDepPerson(this.selected['oid']);
    }
    getDepPerson(oid?) {
        this.publicService.getApprovers(oid).subscribe(res => {
            if (!res) {
                this.options['departments'] = [];
            }else {
                this.options['departments'] = res;
                this.formObj.acceptor_pid = res[0]['pid'];
                this.formObj.acceptor = res[0]['name'];
            }
        });
    }
    restOccurTime() {
        this.formObj.occurrence_time = PUblicMethod.formateEnrtyTime(this.formObj.occurrence_time);
    }
    save() {
        this.addSelectedName();
        this.filterOptionName();
        this.restOccurTime();
        this.onSelectedDepartment();
        this.formObj.status = '待接受';
        this.rfsService.saveTicket( this.formObj ).subscribe(res => {
            if ( res === '00000' ) {
                this.message = [];
                this.message.push({severity: 'success', summary: '消息提示', detail: '保存成功'});
                window.setTimeout(() => {
                    this.router.navigateByUrl('/index/reqForService/rfsBase/serviceOverview');
                }, 1100);
            }else {
                this.message = [];
                this.message.push({severity: 'error', summary: '消息提示', detail: `保存失败${res}`});
            }
        });
    }
    showError() {
        this.message = [];
        this.message.push({severity: 'error', summary: '错误消息提示', detail: '请填写完整表单'});
    }
    get Submitter() {
        return this.myForm.controls['submitter'].untouched && this.myForm.controls['submitter'].hasError('required');
    }
    get title() {
        return this.myForm.controls['title'].untouched && this.myForm.controls['title'].hasError('required');
    }
    get content() {
        return this.myForm.controls['content'].untouched && this.myForm.controls['content'].hasError('required');
    }
    get acceptor() {
        return this.myForm.controls['acceptor'].untouched && this.myForm.controls['acceptor'].hasError('required');
    }
    submitPost(paper) {
        this.addSelectedName();
        this.filterOptionName();
        this.restOccurTime();
        this.rfsService.submitTicket( paper ).subscribe(res => {
            if ( res === '00000' ) {
                this.message = [];
                this.message.push({severity: 'success', summary: '消息提示', detail: '操作成功'});
                window.setTimeout(() => {
                    this.router.navigateByUrl('/index/reqForService/rfsBase/serviceOverview');
                }, 1100);
            }else {
                this.message = [];
                this.message.push({severity: 'error', summary: '消息提示', detail: `操作失败${res}`});
            }
        });
    }
    getTirckMessage(sid) {
        this.rfsService.getTrick(sid).subscribe(res => {
            console.log(res);
            this.formObj.fromx = res['fromx'];
            this.formObj.status = res['status'];
            this.formObj.creator = res['creator'];
            this.formObj.create_time = res['create_time'];
            this.formObj.type = res['type'];
            this.formObj.submitter = res['submitter'];
            this.formObj.submitter_pid = res['submitter_pid'];
            this.formObj.submitter_org_oid = res['submitter_org_oid'];
            this.formObj.submitter_org = res['submitter_org'];
            this.formObj.submitter_phone = res['submitter_phone'];
            this.formObj.occurrence_time = res['occurrence_time'];
            this.formObj.deadline = res['deadline'];
            this.formObj.bt_system = res['bt_system'];
            this.formObj.influence = res['influence'];
            this.formObj.urgency = res['urgency'];
            this.formObj.priority = res['priority'];
            this.formObj.title = res['title'];
            this.formObj.content = res['content'];
            this.formObj.service = res['service'];
            this.formObj.devices = res['devices'];
            this.formObj.acceptor_org = res['acceptor_org'];
            this.formObj.acceptor_org_oid = res['acceptor_org_oid'];
            this.formObj.acceptor = res['acceptor'];
            this.formObj.acceptor_pid = res['acceptor_pid'];
            this.defaultOption['fromx'] = res['fromx'];
            this.defaultOption['type'] = res['type'];
            this.defaultOption['bt_system'] = res['bt_system'];
            this.defaultOption['influence'] = res['influence'];
            this.defaultOption['urgency'] = res['urgency'];
            this.defaultOption['acceptor'] = res['acceptor'];
            this.defaultOption['acceptor_name'] = res['acceptor'];
            this.defaultOption['acceptor_pid'] = res['acceptor_pid'];
            this.hasAccepterOrg(res['acceptor_org_oid']);
            this.clearDefaultOption();
        });
        this.rfsService.getFlowChart(this.formObj.status).subscribe(res => {
            this.eventBusService.rfs.next(res);
        });
    }
    goBack() {
        this.router.navigate(['../serviceOverview'], {relativeTo: this.activatedRouter});
    }
    hasAccepterOrg(oid) {
        if (oid) {
            this.getDepPerson(this.formObj.acceptor_org_oid);
        }
    }
    clearDefaultOption() {
        this.formObj.acceptor && (this.formObj.acceptor = null);
        this.formObj.urgency && (this.formObj.urgency = null);
        this.formObj.fromx && (this.formObj.fromx = null);
        this.formObj.type && (this.formObj.type = null);
        this.formObj.bt_system && (this.formObj.bt_system = null);
        this.formObj.influence && (this.formObj.influence = null);
    }
    onSelectedDepartment() {
        let msg = this.formObj.acceptor;
        if (typeof this.formObj.acceptor === 'string' && this.defaultOption['acceptor_name']) {
            this.formObj.acceptor = this.defaultOption['acceptor_name'];
            this.formObj.acceptor_pid = this.defaultOption['acceptor_pid'];
        }else if (typeof this.formObj.acceptor === 'object') {
            this.formObj.acceptor = msg['name'];
            this.formObj.acceptor_pid = msg['pid'];
        }
    }
    addSelectedName() {
        (!this.formObj.acceptor) && (this.formObj.acceptor = this.defaultOption['acceptor']);
        (!this.formObj.urgency) && (this.formObj.urgency = this.defaultOption['urgency']);
        (!this.formObj.fromx) && (this.formObj.fromx = this.defaultOption['fromx']);
        (!this.formObj.type) && (this.formObj.type = this.defaultOption['type']);
        (!this.formObj.bt_system) && (this.formObj.bt_system = this.defaultOption['bt_system']);
        (!this.formObj.influence) && (this.formObj.influence = this.defaultOption['influence']);
    }
    filterOptionName() {
        if (this.formObj.fromx['name']) {
            this.formObj.fromx = this.formObj.fromx['name'];
        }
        if (this.formObj.type['name']) {
            this.formObj.type = this.formObj.type['name'];
        }
        if (this.formObj.bt_system['name']) {
            this.formObj.bt_system = this.formObj.bt_system['name'];
        }
        if (this.formObj.influence['name']) {
            this.formObj.influence = this.formObj.influence['name'];
        }
        if (this.formObj.urgency['name']) {
            this.formObj.urgency = this.formObj.urgency['name'];
        }
    }

}
